import React, { useEffect, useState } from "react";
import axios from 'axios';
import PubSub from 'pubsub-js';

export default function HeroList() {
  //声明状态
  let [heros, setHeros] = useState([]);
   //组件挂载的钩子
   useEffect(() => {
    axios.get('http://api.xiaohigh.com/heros').then(res => {
      setHeros(res.data);
    });
  }, []);

  //组件挂载完成的钩子
  useEffect(() => {
    PubSub.subscribe('keyword', (channel, data) => {
      //发送请求
      axios.get('http://api.xiaohigh.com/heros', {
        params: {
          name_like: data
        }
      }).then(res => {
        setHeros(res.data);
      })
    });
    //组件卸载时, 取消订阅
    return () => {
      PubSub.unsubscribe('keyword');
    }
  }, [])

  return (
    <div className="row">
      {heros.map((item) => {
        return (
          <div className="hero-item" key={item.id}>
            <img width="100%" src={"http://cdn.xiaohigh.com" + item.image} />
            <p className="text-center">{item.name}</p>
          </div>
        );
      })}
    </div>
  );
}
